import { Modal } from 'antd';
import { orderBy } from 'lodash';

//取小数位
function getDecimalPart(num) {
  let str = '';
  if (typeof num == 'number') {
    str = num.toFixed(2).toString();
  } else {
    str = num + '';
  }
  const parts = str.split('.');
  return parts[1] || '';
}

function handledynamicquerydata(response) {
  const api_param = response?.data?.data[0]?.api_param;
  const api_param_obj = JSON.parse(api_param);
  console.log(api_param_obj);
  const where = [];
  let orderBy = '';
  let paging = {};
  const paramList = api_param_obj?.paramList || [];
  paramList.map((e, i) => {
    switch (e?.name) {
      case 'where': //查询条件
        let element = e.element || [];
        let searchConfigListNew = [];
        element.map((el, il) => {
          let ele = {
            title: el?.label,
            align: 'center',
            key: el?.feild,
            dataIndex: el?.feild,
            hideInTable: true,
            connector: el?.connector,
          };
          switch (el.type) {
            case 'text':
              break;
            case 'checkbox':
            case 'select':
              //多选
              ele.valueType = el.type;
              ele.fieldProps = {
                options: el.option,
              };
              break;
            default:
              break;
          }
          where.push(ele);
        });
        break;
      case 'orderBy': //排序
        orderBy = e.value;
        break;
      case 'paging': //分页
        paging = e.value;
        break;
    }
  });

  return {
    where,
    orderBy,
    paging,
  };
}

function handledynamicqueryColumns(rescolumns) {
  const columnsn = [];
  rescolumns.map((e, i) => {
    let display_format = e['display_format'] ? JSON.parse(e['display_format']) : {};

    let type = display_format?.format?.render?.type || '';
    if (!e.is_hide) {
      let itemcolum = {
        title: () => {
          return <div style={{ textAlign: 'center', wordWrap: 'break-word' }}>{e['title']}</div>;
        },
        align: e.align_type,
        hideInSearch: true,
        dataIndex: e['column_name'],
        key: e['column_name'],
        width: (display_format['format'] && display_format['format']['width']) || 100,
      };
      if (display_format['format'] && display_format['format']['fixed']) {
        itemcolum['fixed'] = display_format['format'] && display_format['format']['fixed'];
      }
      switch (type) {
        case 'datetime':
          itemcolum['render'] = (text, record, index) => {
            let date_format =
              (display_format['format'] && display_format['format']['render']['date_format']) ||
              'YYYY-MM-DD';
            // return date_format;
            return moment(text).format(date_format);
          };
          break;
        case 'map':
          itemcolum['render'] = (text, record, index) => {
            let option =
              (display_format['format'] && display_format['format']['render']['option']) || false;
            let txttype = typeof option[text];
            let color =
              option[text] && txttype != 'string' && option[text]['color']
                ? option[text]['color']
                : '';
            try {
              return (
                <div style={color ? { color: color } : {}}>
                  {txttype == 'string' && option[text]
                    ? option[text] || text
                    : option && option[text]['text']}
                </div>
              );
            } catch (error) {
              console.log(error);
              return <div>{text}</div>;
            }
          };
          break;
        default:
          itemcolum['render'] = (text, record, index) => {
            return (
              <div
                title={text}
                className="ellipsis"
                style={{
                  width:
                    (display_format['format'] && display_format['format']['width'] + 'px') ||
                    '100px',
                }}
                onClick={() => {
                  Modal.info({
                    title: e['title'],
                    content: text,
                  })
                  console.log(text);
                }}
              >
                {text}
              </div>
            );
          };
          break;
      }
      columnsn.push(itemcolum);
    }
  });
  return columnsn;
}
function addThousandSeparator(number) {
  if (!number) {
    return '0';
  }
  // 将数字转换为字符串
  let numStr = number + ''.toString();
  numStr = numStr.trim();
  if (numStr % 1 != 0) {
    numStr = Number(numStr).toFixed(2);
  }

  // 匹配整数部分和小数部分
  const parts = numStr.split('.');
  // 整数部分加入千位分隔符
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  // 重新组合整数部分和小数部分
  return parts.join('.');
}

const handleTreeList = (menus) => {
  // 首先按照sno字段对菜单数组进行排序
  menus.sort((a, b) => a.sno - b.sno);
  // 构建一个以supMenu为键的映射，映射值为菜单项的数组
  const menuMap = menus.reduce((acc, menu) => {
    if (!acc[menu.supMenu]) {
      acc[menu.supMenu] = [];
    }
    acc[menu.supMenu].push(menu);
    return acc;
  }, {});
  // 定义递归函数来构建树形结构
  function buildTree(menus, parentKey = '') {
    return menus
      .filter((menu) => menu.supMenu === parentKey)
      .map((menu) => {
        let children = buildTree(menus, menu.menuId); // 递归构建子菜单
        if (children.length > 0) {
          return Object.assign({}, menu, {
            children: buildTree(menus, menu.menuId), // 递归构建子菜单
          });
        } else {
          return Object.assign({}, menu);
        }
      });
  }
  // 构建树形结构
  const tree = buildTree(menus);
  return tree;
};



const handleOrgTreeList = (list) => {
  console.log(list);
  // 首先按照sno字段对菜单数组进行排序
  list.sort((a, b) => a.gzw_org_no - b.gzw_org_no);
  // 构建一个以suporg为键的映射，映射值为菜单项的数组
  const orgMap = list.reduce((acc, org) => {
    if (!acc[org.parent_company_no]) {
      acc[org.parent_company_no] = [];
    }
    acc[org.parent_company_no].push(org);
    return acc;
  }, {});
  // 定义递归函数来构建树形结构
  function buildTree(list, parentKey = '') {
    return list
      .filter((org) => org.parent_company_no === parentKey)
      .map((org) => {
        let children = buildTree(list, org.gzw_org_no); // 递归构建子菜单
        if (children.length > 0) {
          return Object.assign({}, org, {
            children: buildTree(list, org.gzw_org_no), // 递归构建子菜单
          });
        } else {
          return Object.assign({}, org);
        }
      });
  }
  // 构建树形结构
  const tree = buildTree(list, '100228');
  return tree;
};
function wgsToGcj(lon, lat) {
  let pi = 3.14159265358979324;
  let a = 6378245.0;
  let ee = 0.00669342162296594323;

  /*判断是否在国内，不在国内则不做偏移，因为国外的谷歌地图坐标系是符合WGS84的*/
  function outOfChina(lon, lat) {
    if ((lon < 72.004 || lon > 137.8347) && (lat < 0.8293 || lat > 55.8271)) {
      return true;
    } else {
      return false;
    }
  }

  function transformLat(x, y) {
    let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
    ret += ((20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0) / 3.0;
    ret += ((20.0 * Math.sin(y * pi) + 40.0 * Math.sin((y / 3.0) * pi)) * 2.0) / 3.0;
    ret += ((160.0 * Math.sin((y / 12.0) * pi) + 320 * Math.sin((y * pi) / 30.0)) * 2.0) / 3.0;
    return ret;
  }

  function transformLon(x, y) {
    let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
    ret += ((20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0) / 3.0;
    ret += ((20.0 * Math.sin(x * pi) + 40.0 * Math.sin((x / 3.0) * pi)) * 2.0) / 3.0;
    ret += ((150.0 * Math.sin((x / 12.0) * pi) + 300.0 * Math.sin((x / 30.0) * pi)) * 2.0) / 3.0;
    return ret;
  }

  function transformLonLat(wgLon, wgLat) {
    // 若在国外，不做处理直接返回
    if (outOfChina(wgLon, wgLat)) {
      return [wgLon, wgLat];
    }
    let dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
    let dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
    let radLat = (wgLat / 180.0) * pi;
    let magic = Math.sin(radLat);
    magic = 1 - ee * magic * magic;
    let sqrtMagic = Math.sqrt(magic);
    dLat = (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * pi);
    dLon = (dLon * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * pi);
    return [wgLon + dLon, wgLat + dLat];
  }
  return transformLonLat(lon, lat);
}
function gcjToWgs(lon, lat) {
  let PI = 3.14159265358979324;
  function transformGCJ2WGS(gcjLon, gcjLat) {
    let d = delta(gcjLon, gcjLat);
    return [gcjLon - d.lon, gcjLat - d.lat];
  }

  function delta(x, y) {
    let a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
    let ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
    let dLat = transformLat(x - 105.0, y - 35.0);
    let dLon = transformLon(x - 105.0, y - 35.0);
    let radLat = (y / 180.0) * PI;
    let magic = Math.sin(radLat);
    magic = 1 - ee * magic * magic;
    let sqrtMagic = Math.sqrt(magic);
    dLat = (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * PI);
    dLon = (dLon * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * PI);
    return {
      lat: dLat,
      lon: dLon,
    };
  }
  function transformLat(x, y) {
    let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
    ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
    ret += ((20.0 * Math.sin(y * PI) + 40.0 * Math.sin((y / 3.0) * PI)) * 2.0) / 3.0;
    ret += ((160.0 * Math.sin((y / 12.0) * PI) + 320 * Math.sin((y * PI) / 30.0)) * 2.0) / 3.0;
    return ret;
  }
  function transformLon(x, y) {
    let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
    ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
    ret += ((20.0 * Math.sin(x * PI) + 40.0 * Math.sin((x / 3.0) * PI)) * 2.0) / 3.0;
    ret += ((150.0 * Math.sin((x / 12.0) * PI) + 300.0 * Math.sin((x / 30.0) * PI)) * 2.0) / 3.0;
    return ret;
  }

  return transformGCJ2WGS(lon, lat);
}

const buildTree = (data) => {
  const tree = {};

  data.forEach(item => {
    try {
      // 将行政区划字符串分割为代码和名称
      const code = item.county;
      const county = item.county;
      // 根据行政区划代码和名称构建树
      if (!tree[code]) {
        tree[code] = {
          name: county,
          children: {}
        };
      }

      // 构建第二级节点，即county
      if (!tree[code].children[item.adm_division]) {
        tree[code].children[item.adm_division] = {
          name: item.adm_division,
          children: []
        };
      }

      // 将cmy_id作为第三级节点添加到相应的county下
      tree[code].children[item.adm_division].children.push({
        name: item.cmy_id,
        cm_id: item.cmy_id,
        label: item.cmy_id,
        value: item.cmy_id
      });
    } catch (error) {
      console.log(error);
      console.log(item);
    }

  });

  // 将树的根节点转换为数组
  const treeArray = Object.values(tree).map(node => ({
    name: node.name,
    label: node.name,
    value: node.name,
    children: Object.values(node.children).map(child => ({
      name: child.name,
      label: child.name,
      value: child.name,
      children: child.children
    }))
  }));

  return treeArray;
}
export {
  addThousandSeparator,
  handledynamicquerydata,
  handledynamicqueryColumns,
  handleTreeList,
  wgsToGcj,
  gcjToWgs,
  buildTree,
  handleOrgTreeList
};
